/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxinline.servico;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author laverson
 */
public class ServicoGenerico<T> {

    @PersistenceContext
    private EntityManager entityManager;
    private Class<T> entity;

    public ServicoGenerico(Class<T> entity) {
        this.entity = entity;
    }

    public void salvar(T entity) {
        entityManager.persist(entity);
    }

    public void remover(T entity) {
        T entityToBeRemoved = entityManager.merge(entity);
        entityManager.remove(entityToBeRemoved);
    }

    public void atualizar(T entity) {
        entityManager.merge(entity);
        entityManager.flush();
    }

    public T pesquisar(Long entityID) {
        T e = entityManager.find(entity, entityID);
//        if (e == null) {
//            Msg.messagemInfoRedirect(null, null);
//            return null;
//        }
        return e;
    }

    public List<T> pesquisarTodos() {
        return entityManager.createQuery("select e from " + entity.getSimpleName() + " e").getResultList();
    }

    public EntityManager getEntityManager() {
        return entityManager;
    }

    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    /**
     * Pesquisa os últimos 'limit' registros.
     *
     * @param limit Quantidade de registros a serem retornados. Se o limit for
     * igual a 'null', limit assume valor 10
     */
    public List<T> findLimit(Integer limit) {
        if (limit == null || limit < 0) {
            limit = 10;
        }

        return getEntityManager().createQuery("SELECT e FROM " + entity.getSimpleName() + " e ORDER BY e.id DESC").setMaxResults(limit).getResultList();
    }

    /**
     * Pesquisa os últimos 10 registros.
     */
    public List<T> findLimit() {
        return findLimit(10);
    }
}
